import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math';

class InterestRateCalculatorScreen extends StatefulWidget {
  const InterestRateCalculatorScreen({super.key});

  @override
  State<InterestRateCalculatorScreen> createState() =>
      _InterestRateCalculatorScreenState();
}

class _InterestRateCalculatorScreenState
    extends State<InterestRateCalculatorScreen> {
  final _formKey = GlobalKey<FormState>();
  final _amountController = TextEditingController();
  final _termController = TextEditingController();
  final _rateController = TextEditingController();

  String _termUnit = '年';
  String _repaymentMethod = '等额本息';
  String _calculationResult = '';

  @override
  void dispose() {
    _amountController.dispose();
    _termController.dispose();
    _rateController.dispose();
    super.dispose();
  }

  void _calculate() {
    if (_formKey.currentState!.validate()) {
      final double? amount = double.tryParse(_amountController.text);
      final int? term = int.tryParse(_termController.text);
      final double? annualRate = double.tryParse(_rateController.text);

      if (amount == null || term == null || annualRate == null) {
        setState(() {
          _calculationResult = '请输入有效的数字';
        });
        return;
      }

      final int months = _termUnit == '年' ? term * 12 : term;
      final double monthlyRate = annualRate / 100 / 12;

      double totalInterest = 0;
      double totalRepayment = 0;
      String resultText = '';

      if (_repaymentMethod == '等额本息') {
        if (monthlyRate == 0) {
          final double monthlyPayment = amount / months;
          totalRepayment = amount;
          totalInterest = 0;
          resultText =
              '每月还款: ${monthlyPayment.toStringAsFixed(2)}\n总利息: ${totalInterest.toStringAsFixed(2)}\n还款总额: ${totalRepayment.toStringAsFixed(2)}';
        } else {
          final double monthlyPayment =
              (amount * monthlyRate * pow(1 + monthlyRate, months)) /
                  (pow(1 + monthlyRate, months) - 1);
          totalRepayment = monthlyPayment * months;
          totalInterest = totalRepayment - amount;
          resultText =
              '每月还款: ${monthlyPayment.toStringAsFixed(2)}\n总利息: ${totalInterest.toStringAsFixed(2)}\n还款总额: ${totalRepayment.toStringAsFixed(2)}';
        }
      } else {
        // 等额本金
        double firstMonthPayment = 0;
        double lastMonthPayment = 0;
        totalRepayment = 0;

        for (int i = 0; i < months; i++) {
          final double monthlyPrincipal = amount / months;
          final double monthlyInterest =
              (amount - monthlyPrincipal * i) * monthlyRate;
          final double currentMonthPayment = monthlyPrincipal + monthlyInterest;

          if (i == 0) firstMonthPayment = currentMonthPayment;
          if (i == months - 1) lastMonthPayment = currentMonthPayment;

          totalRepayment += currentMonthPayment;
        }

        totalInterest = totalRepayment - amount;
        resultText =
            '首月还款: ${firstMonthPayment.toStringAsFixed(2)}\n末月还款: ${lastMonthPayment.toStringAsFixed(2)}\n(每月递减)\n总利息: ${totalInterest.toStringAsFixed(2)}\n还款总额: ${totalRepayment.toStringAsFixed(2)}';
      }

      setState(() {
        _calculationResult = resultText;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('贷款利息计算器'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              _buildTextFormField(
                controller: _amountController,
                labelText: '贷款金额(元)',
                icon: Icons.attach_money,
              ),
              const SizedBox(height: 16),
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: _buildTextFormField(
                      controller: _termController,
                      labelText: '贷款期限',
                      isNumber: true,
                      icon: Icons.timer_outlined,
                    ),
                  ),
                  const SizedBox(width: 8),
                  DropdownButton<String>(
                    value: _termUnit,
                    items: <String>['年', '月']
                        .map<DropdownMenuItem<String>>((String value) {
                      return DropdownMenuItem<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                    onChanged: (String? newValue) {
                      setState(() {
                        _termUnit = newValue!;
                      });
                    },
                  ),
                ],
              ),
              const SizedBox(height: 16),
              DropdownButtonFormField<String>(
                value: _repaymentMethod,
                decoration: const InputDecoration(
                  labelText: '还款方式',
                  border: OutlineInputBorder(),
                  prefixIcon: Icon(Icons.payment),
                ),
                items: <String>['等额本息', '等额本金']
                    .map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
                  );
                }).toList(),
                onChanged: (String? newValue) {
                  setState(() {
                    _repaymentMethod = newValue!;
                  });
                },
              ),
              const SizedBox(height: 16),
              _buildTextFormField(
                controller: _rateController,
                labelText: '年化利率(%)',
                icon: Icons.percent,
              ),
              const SizedBox(height: 24),
              ElevatedButton.icon(
                onPressed: _calculate,
                icon: const Icon(Icons.calculate),
                label: const Text('开始计算'),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  textStyle: const TextStyle(fontSize: 18),
                ),
              ),
              const SizedBox(height: 24),
              if (_calculationResult.isNotEmpty)
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.surfaceVariant,
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(
                        color: Theme.of(context).colorScheme.outline),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '计算结果',
                        style: Theme.of(context).textTheme.titleLarge,
                      ),
                      const Divider(height: 20),
                      Text(
                        _calculationResult,
                        style: Theme.of(context)
                            .textTheme
                            .bodyLarge
                            ?.copyWith(height: 1.8),
                      ),
                    ],
                  ),
                )
            ],
          ),
        ),
      ),
    );
  }

  TextFormField _buildTextFormField({
    required TextEditingController controller,
    required String labelText,
    required IconData icon,
    bool isNumber = false,
  }) {
    return TextFormField(
      controller: controller,
      decoration: InputDecoration(
        labelText: labelText,
        prefixIcon: Icon(icon),
        border: const OutlineInputBorder(),
      ),
      keyboardType: const TextInputType.numberWithOptions(decimal: true),
      inputFormatters: isNumber
          ? [FilteringTextInputFormatter.digitsOnly]
          : [FilteringTextInputFormatter.allow(RegExp(r'^\d+\.?\d{0,2}'))],
      validator: (value) {
        if (value == null || value.isEmpty) {
          return '请输入$labelText';
        }
        // return null 的意思是“验证成功”。
        return null;
      },
    );
  }
}
